import time

import requests
from playwright.sync_api import Playwright, sync_playwright, expect


def run(playwright: Playwright) -> None:
    time_sleep = 60
    browser = playwright.chromium.launch(headless=True)
    context = browser.new_context()
    page = context.new_page()
    while True:
        live_id_req = requests.get("http://127.0.0.1:8000/api/dy/un_bound_live")
        live_id = live_id_req.json()['data']['live_id']
        if not live_id:
            print(f"Wait New Live ID time sleep {time_sleep}s")
            time.sleep(time_sleep)
        page.goto(f"https://live.douyin.com/{live_id}")
        time.sleep(1)
        title = page.title()
        live_name = title.replace("的抖音直播间 - 抖音直播", "")
        data = {"live_id": live_id, "live_name": live_name}
        requests.post("http://127.0.0.1:8000/api/dy/live", data=data)

    # ---------------------
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)